import Vue from "vue";
import VueRouter from "vue-router";
import routes from "./routes"

Vue.use(VueRouter);

// 不可以写成VueRouter.prototype.push()的形式，因为后者是调用函数
const orgPush = VueRouter.prototype.push;
const orgReplace = VueRouter.prototype.replace;

// 重写push方法，解决相同路径跳转报错问题
VueRouter.prototype.push = function (location, resolve, reject) {
    if (resolve && reject) {
        orgPush.call(this, location, resolve, reject);
    }
    else {
        orgPush.call(this, location, () => { }, () => { });
    }
}
// 重写replace方法，解决重复点击报错问题
VueRouter.prototype.replace = function (location, resolve, reject) {
    if (resolve && reject) {
        orgReplace.call(this, location, resolve, reject);
    }
    else {
        orgReplace.call(this, location, () => { }, () => { });
    }
}
// 配置路由
let router = new VueRouter({
    routes,
    scrollBehavior(to, from, savedPosition) {
        return { y: 0 }
    }
})

router.beforeEach((to, from, next) => {
    /*当离开聊天页面时，需要将一些session删除 */
    if (from.name == "took" && to.name != 'took') {
        sessionStorage.removeItem('sendNickName');
        sessionStorage.removeItem('avartUrl');
        sessionStorage.removeItem('sendUserId');
        next();
    } else {
        next();
    }
})

export default router;